<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\BuyerTask;
use App\Models\Task;
use App\Models\BuyerTaskLog;
use Auth,DB;

class BuyerTaskController extends Controller
{
    
    /**
     * 我的任务
     */
    public function myTask(Request $request)
    {
    	$rs['status'] = false;
    	$map['buyer_id'] = Auth::user()->buyer->id;
        
        //dd(Auth::user()->buyer);
        $query =  BuyerTask::where($map);
        if($request->status == 0) {
            $query = $query->WhereIn('status',[0,50]);
        }

        if($request->status == 100) {
            $query = $query->WhereIn('status',[100,200]);
        }

        if($request->status == -1) {
            $query = $query->Where('status',-1);
        }
    	
    	$list     = $query->with(['task' => function ($query) {
                $query->withTrashed();
        }])
                          ->paginate(10);
    	if($list){
    		$rs['status'] = true;
    		$rs['data']   = $list;
    		return response()->json($rs);
    	}
    	return response()->json($rs);
    }


    public function show(Request $request)
    {
        $rs['status']    = false;
        $map['buyer_id'] = Auth::user()->buyer->id;
        $map['id']       = $request->id;
        $data = BuyerTask::where($map)->with('task','seller')->first();
        if($data) {
            $rs['status'] = true;
            $rs['data']   = $data;
            return response()->json($rs);
        }
        return response()->json($rs);
    }

    /**
     * 取消任务
     */
    public function cancle(Request $request)
    {
        $rs['status']    = false;
        $map['buyer_id'] = Auth::user()->buyer->id;
        $map['id']       = $request->id;
       
        $buyerTask = BuyerTask::where($map)->first();
        if(!$buyerTask) {
            $rs['msg'] = '任务不存在';
            return response()->json($rs);
        }

        if($buyerTask->status == 200 || $buyerTask->status == -1) {
            $rs['msg'] = '此任务无法取消';
            return response()->json($rs);
        }

        DB::beginTransaction();
        try{
            BuyerTask::where($map)
                                ->update(['status'=>'-1']);

            $task = Task::find($buyerTask->task_id);
            $task->valid_num = $task->valid_num+1;
            $flag = $task->save();

           
            $log['buyer_task_id'] = $buyerTask->task_id;
            $log['status'] = '-1';
            $log['msg']    = '用户取消';
            $this->buyerTaskLog($log);
                            
        } catch(\Exception $e) {
            DB::rollBack();
            $rs['msg'] = $e->getMessage();

            return back()->withInput()->with('rs',$rs);
        }
        
        
        if($flag) {
            DB::commit();
            $rs['status'] = true;
            //$rs['data']   = $task;
            $rs['msg']    = '任务取消成功';
            return response()->json($rs);
        }
            DB::rollBack();
            $rs['msg'] = '操作失败';

      
        return response()->json($rs);
    }

    /**
     * 完成任务
     */
    public function doneTask(Request $request)
    {
        $rs['status'] = false;
        $map['buyer_id'] = Auth::user()->buyer->id;
        $map['task_id']  = $request->task_id;
        //dd($map);
        $bt = BuyerTask::where($map)->first();

        if(in_array($bt->status, ['-1','200']) ) {
            $rs['msg'] = '任务状态异常：'.$bt->status;
            return response()->json($rs);
        }



        if($bt) {

            // 如果状态为0 那么订单号和付款图必须同时传
            if ($bt->status == 0 ){
                
                if (!$request->pay_pic || !$request->ordercode) {
                    $rs['msg'] = '订单号和付款截图必须同时是上传';
                    return response()->json($rs);
                }
            }

            if($request->ordercode) {
               $data['ordercode']   = $request->ordercode; 
            }
            

            if ($request->has('pay_pic')) {
                $ext      = $request->pay_pic->extension();
                $filename = date('ymd').str_random(10).'_pay.'.$ext;
                $request->pay_pic->storeAs('public/task/'.$request->task_id, $filename);
                $data['pay_pic'] = '/storage/task/'.$request->task_id.'/'.$filename;
            }

            if ($request->has('comment_pic')) {
                $ext      = $request->comment_pic->extension();
                $filename = date('ymd').str_random(10).'_comment.'.$ext;
                $request->comment_pic->storeAs('public/task/'.$request->task_id, $filename);
                $data['comment_pic'] = '/storage/task/'.$request->task_id.'/'.$filename;
            }
            
            // 如果上传了订单号和付款图并且之前的状态是50
        if($request->ordercode && $request->pay_pic && ($bt->status == 0 ))  {
                $data['status'] = '50';
                $data['payed_at'] = date('Y-m-d H:i:s');
        }

            // 上传评论图 的时候就把状态改为100
        if( ($bt->status=='50') && $request->comment_pic) {
            $now     = time();
            $paytime = strtotime($bt->payed_at);
            // 付款两天之后才能上传评论图
            // if($now-$paytime<60*60*48) {
            //     $rs['msg'] = '付款两天之后才能上传评论图';
            //     return response()->json($rs);
            // }
            $data['status'] = '100';
            $data['commented_at'] = date('Y-m-d H:i:s');
        }

            BuyerTask::where($map)->update($data);

            $log['buyer_task_id'] = $bt->id;
            $log['status'] = array_get($data,'status',$bt->status);
            $log['buyer_id'] = $bt->buyer_id;
            $log['msg']    = '提交成功';
            $flag =  $this->buyerTaskLog($log);

            if($flag) {
                $rs['status'] = true;
                $rs['msg']    = '提交成功';
                return response()->json($rs);
            }

        } else {
            $rs['msg'] = '任务不存在';
        }

        
        return response()->json($rs);
    }
}
